package cn.xlbweb.admincloud.filter;

import java.nio.charset.StandardCharsets;

import cn.xlbweb.admincloud.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * @author: bobi
 * @date: 2019-06-23 14:13
 * @description:
 */
@Slf4j
@Component
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("认证开始");
        Route route = exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        log.info("网关信息:{}", route);
        ServerHttpRequest request = exchange.getRequest();
        // 获取header信息
        String authorization = request.getHeaders().getFirst(JwtUtils.HEADER_AUTH);
        if (StringUtils.isBlank(authorization)) {
            log.error("Authorization不能为空");
            return response(exchange, -1, "Authorization不能为空");
        }
        // 校验header信息
        String userId = JwtUtils.parseToken(authorization);
        ServerHttpRequest.Builder mutate = request.mutate();
        String dbUserId = "666666";
        if (dbUserId.equals(userId)) {
            mutate.header("x-user-id", userId);
            mutate.header("x-user-serviceName", route.getUri().getHost());
        } else {
            log.error("用户不存在");
            return response(exchange, -1, "用户不存在");
        }
        log.info("认证通过,正在转发请求");
        ServerHttpRequest buildRequest = mutate.build();
        return chain.filter(exchange.mutate().request(buildRequest).build());
    }

    private Mono<Void> response(ServerWebExchange exchange, Integer status, String message) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", status);
        jsonObject.put("message", message);
        byte[] bits = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
